<template>
  <div class="register-page">
    <!-- 背景层 -->
    <div class="background-layer">
      <img :src="backgroundImage" alt="注册背景" class="background-image" />
    </div>

    <!-- 内容层 -->
    <div class="content-container">
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        class="register-form"
      >
        <h2 class="form-title">用户注册</h2>

        <el-form-item label="账号" prop="account">
          <el-input v-model="registerForm.account" placeholder="请输入账号" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="身份证号码" prop="idcard">
          <el-input
            v-model="registerForm.idcard"
            placeholder="请输入身份证号码"
          />
        </el-form-item>

        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="registerForm.roles[0].roleId"
            placeholder="请选择角色"
          >
            <el-option label="租户" :value="3" />
            <el-option label="房东" :value="2" />
          </el-select>
        </el-form-item>

        <div class="form-actions">
          <el-button type="primary" @click="handleRegister">{{
            loading ? "注册中..." : "注册完成"
          }}</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import backgroundImage from "@/assets/background.jpg";
import api from "@/api";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
const registerFormRef = ref(null);
const loading = ref(false);

const registerForm = reactive({
  account: "",
  password: "",
  nickname: "",
  phone: "",
  email: "",
  name: "",
  idcard: "",
  confirmPassword: "",
  roles: [
    {
      roleId: 1,
    },
  ],
});

const registerRules = reactive({
  account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "input"], // 增加输入时实时验证
    },
  ],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  idcard: [
    { required: true, message: "身份证号码不能为空", trigger: "blur" },
    {
      pattern: /^\d{15}(\d{2}[0-9Xx])?$/,
      message: "请输入有效的身份证号码",
      trigger: "blur",
    },
  ],
  roles: [{ required: true, message: "请选择角色", trigger: "change" }],
});

const handleRegister = async () => {
  console.log("注册数据:", registerForm);
  try {
    loading.value = true;
    await nextTick();

    if (!registerFormRef.value) {
      throw new Error("注册表单未正确初始化");
      return;
    }

    // 执行Element Plus表单验证
    const valid = await registerFormRef.value.validate().catch((err) => {
      console.error("表单验证失败:", err);
      return false;
    });
    if (!valid) {
      ElMessage.warning("请正确填写所有表单字段");
      return;
    }
    // 移除确认密码字段
    const { confirmPassword, ...submitData } = registerForm;
    // 发送注册请求
    const { data } = await api.auth.register(submitData);

    // 处理注册成功
    ElMessage.success("注册成功");
    router.push({ name: "Login" });
  } catch (error) {
    console.error("注册失败:", error);
    // 增强错误处理
    if (error.message.includes("表单引用")) {
      console.error("表单DOM未正确挂载");
      ElMessage.error("表单初始化失败，请刷新页面");
    }
    if (error.response?.data) {
      const { code, message } = error.response.data;
      if (code === 400) {
        ElMessage.error(message || "用户已存在");
      }
    } else {
      ElMessage.error(error.message || "网络请求失败");
    }
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  registerFormRef.value.resetFields();
};
</script>

<style scoped lang="css">
.login-page {
  position: relative;
  min-height: 100vh;
}

.background-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.background-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  filter: brightness(0.92) blur(2px);
}

.content-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  max-width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.login-form,
.reset-password-form {
  width: 100%;
}

.form-title {
  font-size: 1.8rem;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #34495e !important;
}

:deep(.el-input__inner) {
  background: #f8f9fa;
  border-radius: 6px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-container {
    padding: 30px;
  }

  .form-title {
    font-size: 1.5rem;
  }
}
</style>
